#include "../include/user.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>

// 初始化用户列表
UserList* init_user_list(int max_count) {
    UserList *list = (UserList*)malloc(sizeof(UserList));
    if (!list) return NULL;
    
    list->users = (User*)malloc(sizeof(User) * max_count);
    if (!list->users) {
        free(list);
        return NULL;
    }
    
    list->count = 0;
    list->max_count = max_count;
    pthread_mutex_init(&list->mutex, NULL);
    
    return list;
}

// 清理用户列表
void cleanup_user_list(UserList *list) {
    if (list) {
        if (list->users) {
            free(list->users);
        }
        pthread_mutex_destroy(&list->mutex);
        free(list);
    }
}

// 注册新用户
bool register_user(UserList *list, const char *username, const char *password) {
    if (!list || !username || !password) return false;
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 检查用户是否已存在
    for (int i = 0; i < list->count; i++) {
        if (strcmp(list->users[i].username, username) == 0) {
            pthread_mutex_unlock(&list->mutex);
            return false; // 用户已存在
        }
    }
    
    // 检查是否有足够空间
    if (list->count >= list->max_count) {
        pthread_mutex_unlock(&list->mutex);
        return false; // 用户数量已达上限
    }
    
    // 添加新用户
    strcpy(list->users[list->count].username, username);
    strcpy(list->users[list->count].password, password);
    list->users[list->count].socket_fd = -1;
    list->users[list->count].online = false;
    list->count++;
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    return true;
}

// 用户登录
User* login_user(UserList *list, const char *username, const char *password, int socket_fd) {
    if (!list || !username || !password) return NULL;
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 查找用户并验证密码
    for (int i = 0; i < list->count; i++) {
        if (strcmp(list->users[i].username, username) == 0 && 
            strcmp(list->users[i].password, password) == 0) {
            
            // 更新用户状态
            list->users[i].socket_fd = socket_fd;
            list->users[i].online = true;
            
            // 解锁
            pthread_mutex_unlock(&list->mutex);
            
            return &list->users[i];
        }
    }
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    return NULL; // 用户名或密码错误
}

// 用户登出
bool logout_user(UserList *list, const char *username) {
    if (!list || !username) return false;
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 查找用户
    for (int i = 0; i < list->count; i++) {
        if (strcmp(list->users[i].username, username) == 0) {
            // 更新用户状态
            list->users[i].socket_fd = -1;
            list->users[i].online = false;
            
            // 解锁
            pthread_mutex_unlock(&list->mutex);
            
            return true;
        }
    }
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    return false; // 用户不存在
}

// 从文件加载用户数据
bool load_users_from_file(UserList *list, const char *file_path) {
    if (!list || !file_path) return false;
    
    FILE *fp = fopen(file_path, "r");
    if (!fp) {
        // 文件不存在，创建空文件
        fp = fopen(file_path, "w");
        if (fp) {
            fclose(fp);
        }
        return true;
    }
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 读取用户数据
    char line[256];
    while (fgets(line, sizeof(line), fp) != NULL) {
        char username[50], password[50];
        if (sscanf(line, "%s %s", username, password) == 2) {
            // 检查是否有足够空间
            if (list->count >= list->max_count) {
                break;
            }
            
            // 添加用户到列表
            strcpy(list->users[list->count].username, username);
            strcpy(list->users[list->count].password, password);
            list->users[list->count].socket_fd = -1;
            list->users[list->count].online = false;
            list->count++;
        }
    }
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    fclose(fp);
    return true;
}

// 保存用户数据到文件
bool save_users_to_file(UserList *list, const char *file_path) {
    if (!list || !file_path) return false;
    
    FILE *fp = fopen(file_path, "w");
    if (!fp) return false;
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 写入用户数据
    for (int i = 0; i < list->count; i++) {
        fprintf(fp, "%s %s\n", list->users[i].username, list->users[i].password);
    }
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    fclose(fp);
    chmod(file_path, 0600); // 设置权限为仅用户可读写
    return true;
}

// 获取在线用户列表
char* get_online_users(UserList *list) {
    if (!list) return NULL;
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 计算所需空间
    int total_len = 1;
    for (int i = 0; i < list->count; i++) {
        if (list->users[i].online) {
            total_len += strlen(list->users[i].username) + 2;
        }
    }
    
    // 分配内存
    char *result = (char*)malloc(total_len);
    if (!result) {
        pthread_mutex_unlock(&list->mutex);
        return NULL;
    }
    
    // 构建在线用户列表
    result[0] = '\0';
    for (int i = 0; i < list->count; i++) {
        if (list->users[i].online) {
            if (strlen(result) > 0) {
                strcat(result, ", ");
            }
            strcat(result, list->users[i].username);
        }
    }
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    return result;
}

// 根据用户名查找用户
User* find_user_by_username(UserList *list, const char *username) {
    if (!list || !username) return NULL;
    
    // 加锁保护共享资源
    pthread_mutex_lock(&list->mutex);
    
    // 查找用户
    User *user = NULL;
    for (int i = 0; i < list->count; i++) {
        if (strcmp(list->users[i].username, username) == 0) {
            user = &list->users[i];
            break;
        }
    }
    
    // 解锁
    pthread_mutex_unlock(&list->mutex);
    
    return user;
}
